/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package terminal.model;

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortException;

/**
 *
 * @author prpo4526
 */
public class SerialPortDataListener implements jssc.SerialPortEventListener
{
    public SerialPortDataListener( SerialPort serialPort, SerialPortDataProcessor serialPortDataProcessor ) 
    {
        m_serialPort = serialPort;
        m_serialPortDataProcessor = serialPortDataProcessor;
    }
    
    public void setSerialPort( jssc.SerialPort serialPort ) throws SerialPortException
    {
        m_serialPort = serialPort;
        
        if ( null != m_serialPort )
        {
            m_serialPort.addEventListener( this );
        }
    }
    
    @Override public void serialEvent( SerialPortEvent event )
    {
        if ( event.isRXCHAR() )
        {
            if ( null != m_serialPortDataProcessor )
            {
                m_serialPortDataProcessor.addBytes( readBytesFromSerialBuffer() );
            }
        }
    }
    
    private byte[] readBytesFromSerialBuffer()
    {
        byte[] result = null;
        
        try 
        {
            if ( null != m_serialPort )
            {
                result = m_serialPort.readBytes();              
            }                    
        }
        catch ( SerialPortException ex ) 
        {
            System.out.println(ex);
        }
        
        return result;        
    }
    
    private String readStringFromSerialBuffer()
    {        
        return new String( readBytesFromSerialBuffer() );
    }
        
    jssc.SerialPort m_serialPort;
    SerialPortDataProcessor m_serialPortDataProcessor;
}
